import React, { useState, useEffect } from 'react';
import Login from '@/pages/Login';
import MainLayout from '@/pages/MainLayout';
import { isAuthenticated } from '@/utils/auth'; // 使用路径别名
import { useLocation } from 'react-router-dom';
import SlDraggableTopBar from "@/components/SlDraggableTopBar";
import './App.css';

const App: React.FC = () => {
    const [isLoggedIn, setIsLoggedIn] = useState<boolean | null>(null);
    const [isChecking, setIsChecking] = useState(true);
    const location = useLocation();

    useEffect(() => {
        const checkAuth = () => {
            try {
                const authenticated = isAuthenticated();
                setIsLoggedIn(authenticated);
            } catch (error) {
                setIsLoggedIn(false);
            } finally {
                setIsChecking(false);
            }
        };

        checkAuth();
    }, []);

    const handleLoginSuccess = () => {
        setIsLoggedIn(true);
    };

    const handleLogout = () => {
        setIsLoggedIn(false);
    };

    // 显示加载状态
    if (isChecking || isLoggedIn === null) {
        return (
            <div className="loading-container">
                <div className="loading-animation">
                    <div className="spinner"></div>
                    <p>正在检查登录状态...</p>
                </div>
            </div>
        );
    }

    return (
        <div className="w-full h-full">
            <SlDraggableTopBar/>
            <div className={"h-[calc(100%_-_48px)]"}>
                {isLoggedIn ? (
                    <MainLayout onLogout={handleLogout} />
                ) : (
                    <Login onLoginSuccess={handleLoginSuccess} />
                )}
            </div>
        </div>
    );
};

export default App;
